package com.ruix.app.ui.app;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.model.WebParcel;
import com.ruix.app.network.ApiConstant;
import com.ruix.app.ui.CommonWebActivity;
import com.ruix.app.ui.adapter.PhotoViewAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.stratum.ReleasePostsActivity;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.PhotoView;
import com.ruix.app.util.QRCodeDecoder;
import com.ruix.app.util.ShareUtil;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.XCircleIndicator;
import com.ruix.app.widget.dialog.SavePhotoDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by hadexs on 2017/5/17.
 */

public class PhotoViewActivity extends BaseActivity implements PhotoViewAdapter.LoadPhotoListener, SavePhotoDialog.SavePhotoListener {


    private ViewPager viewPager;
    private PhotoViewAdapter adapter;
    private int curentPosition;
    private ArrayList<String> addrss;
    private XCircleIndicator indicator;
    private ProgressBar progressBar;
    private SavePhotoDialog dialog;


    public static Intent getInstance(Context context, int position, ArrayList<String> addrssUrl) {
        Intent intent = new Intent(context, PhotoViewActivity.class);
        intent.putExtra(PhotoView.EXTRA_CURRENT_ITEM, position);
        intent.putExtra(PhotoView.EXTRA_PHOTOS, addrssUrl);
        return intent;
    }


    @Override
    protected void beforeOnCreate() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
    }

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_photo_view;
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected boolean isUseTransStatusBar() {
        return false;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            curentPosition = intent.getIntExtra(PhotoView.EXTRA_CURRENT_ITEM, 0);
            addrss = intent.getStringArrayListExtra(PhotoView.EXTRA_PHOTOS);
        }
        if (addrss == null) {
            finish();
            return;
        }
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        indicator = (XCircleIndicator) findViewById(R.id.xCircleIndicator);
        if (addrss.size() == 1) {
            indicator.setVisibility(View.GONE);
        }
        indicator.initData(addrss.size(), 5);// 设置总共的页数
        indicator.setCurrentPage(curentPosition);// 设置当前所在页面
        viewPager = (ViewPager) findViewById(R.id.vp_photos);
        adapter = new PhotoViewAdapter(this, addrss);
        adapter.setLoadPhotoListener(this);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(curentPosition);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicator.setCurrentPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initLocalData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    public void startLoading() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void loadingFinish() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void longClick(int curentPosition) {
        if (dialog == null) {
            dialog = new SavePhotoDialog(this);
            dialog.setSavePhotoListener(this);
        }
        dialog.show(curentPosition);
        decode(curentPosition);
        //// TODO: 2017/5/24  识别图片

    }

    @Override
    public void onTapClick() {
        if (!isFinishing()) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void decode(final int position) {
        String imageurl = addrss.get(position);
        Glide.with(RuiApplication.getAppContext()).load(imageurl).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                String qurcode = QRCodeDecoder.syncDecodeQRCode(resource.getPath());
//                LogUitl.e("");
                if (!TextUtils.isEmpty(qurcode)) {
                    dialog.setQrcodeValue(qurcode);
                }

            }
        });


    }

    @Override
    public void savePhoto(int position) {
        String imageurl = addrss.get(position);
        Glide.with(RuiApplication.getAppContext()).load(imageurl).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                try {
                    if (resource != null) {
                        FileInputStream fileInputStream = new FileInputStream(resource);
                        Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
                        saveImageToGallery(PhotoViewActivity.this, bitmap);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
//                insertImage(resource);
            }
        });
    }

    @Override
    public void decodeQrcode(String qrcode) {
        if (!TextUtils.isEmpty(qrcode)) {
            if (qrcode.startsWith("http") || qrcode.startsWith("www")) {
                WebParcel parcel = new WebParcel();
                parcel.setTitle("");
                parcel.setUrl(qrcode);
                startActivity(CommonWebActivity.newIntent(this, parcel));
            } else {
                Intent intent = QrcodeTipActivity.getInstance(this, qrcode);
                startActivity(intent);
            }
        }
    }

//    private void saveBarcode(){
//        barCodeView.setDrawingCacheEnabled(true);
//        barCodeView.buildDrawingCache();  //启用DrawingCache并创建位图
//        Bitmap bitmap = Bitmap.createBitmap(barCodeView.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
//        barCodeView.setDrawingCacheEnabled(false);
//        saveImageToGallery(getApplicationContext(),bitmap);
//    }


    public  void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        //申请权限
        if (!checkCameraPermission()){
            return;
        }

        File appDir = new File(Environment.getExternalStorageDirectory(), "ruixue_pic");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        String path = file.getAbsolutePath();


        Uri uri = Uri.fromFile(file);
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
        ToastUtil.showNewSuccessMsg("保存成功");
    }


    private void insertImage(File resource) {
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    resource.getAbsolutePath(), resource.getName(), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        String path = resource.getAbsolutePath();
        // 最后通知图库更新
//        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

        Uri uri = Uri.fromFile(resource);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        ToastUtil.showNewSuccessMsg("保存成功");
    }


    public boolean checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int aPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || aPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(PhotoViewActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

}
